<?php
/**
 * HX<titanrain@163.com>
 */
class CategoryService{

    public static function getAllCategorys(){
        //categorys(system|user)
        $sysCategory = CategoryService::getSysCategorys();
        $userCategory = CategoryService::getUserCategorys();
        $data = array();
        foreach($sysCategory as $s){
            $data[] = array('id'=>$s['category_id'],'name'=>$s['name']);
        }
        foreach($userCategory as $u){
            $data[] = array('id'=>$u['category_id'],'name'=>$u['name']);
        }
        return $data;
    }
    
    public static function userUsedCategorys($userId = 0){
    	$categoryIdArr = UserBookAR::userUserdCategoryIds($userId);
    	return CategoryAR::batchGetByCategoryIds($categoryIdArr);
    }

    public static function getSysCategorys(){
        return CategoryAR::querySysAll();
    }

    public static function getUserCategorys(){
        $userId = User::id();
        return CategoryAR::queryByUserId($userId);
    }

    public static function create($categoryName){
        $userId = User::id();
        if($userId === 0){
            return array('success'=>false,'message'=>'请先登录');
        }
        $categoryName = mysql_escape_string($categoryName);
        $cnt = DBUtil::count(CategoryAR::tblName(),"fk_user=$userId and name='$categoryName'");
        if($cnt>0){
            return array('success'=>false,'message'=>'分类名称已经存在');
        }
        try{
            $newCategoryId = CategoryAR::saveCategory($categoryName,$userId);
        }catch(Exception $e){
            return array('success'=>false,'message'=>'未知错误，请联系站长');
        }
        return array('success'=>true,'message'=>'ok','data'=>$newCategoryId);
    }
}
